package com.groupwork.resourcemonitoruserserver.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.groupwork.resourcemonitorcommon.common.BaseResponse;
import com.groupwork.resourcemonitorcommon.common.ErrorCode;
import com.groupwork.resourcemonitorcommon.common.ResultUtils;
import com.groupwork.resourcemonitorcommon.exception.BusinessException;
import com.groupwork.resourcemonitormodel.domain.userServer.User;
import com.groupwork.resourcemonitormodel.model.user.UserLoginDTO;
import com.groupwork.resourcemonitormodel.model.user.UserRegisterDTO;
import com.groupwork.resourcemonitoruserserver.mapper.UserMapper;
import com.groupwork.resourcemonitoruserserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    @Autowired
    private PlatformTransactionManager txManager;


    //用户注册
    @Override
    public BaseResponse<Long> userRegister(UserRegisterDTO userRegisterDTO) {
        //获取参数
        String username = userRegisterDTO.getUsername();
        String password = userRegisterDTO.getPassword();
        String checkPassword = userRegisterDTO.getCheckPassword();
        //校验参数
        if (StringUtils.isAnyBlank(username, password, checkPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        //校验长度
        if (username.length() < 4 || username.length() > 20)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误,账号必须大于4位小于20位");
        if (password.length() < 8 || password.length() > 20)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误,密码必须大于8位小于20位");
        //密码和校验密码相同
        if (!password.equals(checkPassword))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            //加密
            //  String encryptPassword = DigestUtils.md5DigestAsHex((password).getBytes());
            //插入数据
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
        } catch (Exception e) {
            //这里是异常处理
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "注册失败");
        }
        txManager.commit(status);
        return ResultUtils.success("注册成功");
    }

    @Override
    public BaseResponse<String> userLogin(UserLoginDTO userLoginDTO) {
        //获取参数
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        //校验参数
        if (StringUtils.isAnyBlank(username, password)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        //校验长度
        if (username.length() < 4 || username.length() > 20)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误,账号必须大于4位小于20位");
        if (password.length() < 8 || password.length() > 20)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误,密码必须大于8位小于20位");
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", password);
        User user = this.baseMapper.selectOne(queryWrapper);
        //用户不存在
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        //签发accessToken

        String token = username;
        return ResultUtils.success(token,"登录成功");
    }



}


